package com.zfast.config.service.Impl;

import com.zfast.config.entity.User;
import com.zfast.config.mapper.AdminMapper;
import com.zfast.config.repository.AdminRepository;
import com.zfast.config.service.AdminService;
import com.zfast.config.vo.PageBean;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * @Classname AdminServiceImpl
 * @Description None
 * @Date 2019/7/16 12:20
 * @Created by WDD
 */
@Service
public class AdminServiceImpl implements AdminService {

    @Resource
    private AdminMapper adminMapper;

    @Resource
    AdminRepository adminRepository;

    @Override
    public User login(String username, String password) {
        User user = User.builder().username(username).password(password).build();
        Example<User> userExample = Example.of(user);
        return adminRepository.findOne(userExample).orElse(null);
    }

    @Override
    public PageBean<User> queryPage(Map<String, Object> paramMap) {
        PageBean<User> pageBean = new PageBean<>((Integer) paramMap.get("pageno"), (Integer) paramMap.get("pagesize"));

        Page<User> all = adminRepository.findAll(PageRequest.of((pageBean.getPageno() - 1), pageBean.getPagesize()));

        pageBean.setDatas(all.getContent());
        pageBean.setTotalsize((int) all.getTotalElements());

        return pageBean;
    }

    @Override
    public int insertAdmin(User user) {
        adminRepository.save(user);
        return 1;
    }

    @Override
    public User selectById(String id) {
        return adminRepository.getById(id);
    }

    @Override
    public int delByAdminIds(List<String> ids) {
        adminRepository.deleteAllByIdInBatch(ids);
        return ids.size();
        //return adminMapper.delByAdminIds(ids);
    }

    @Override
    public int editByAdmin(User user) {
        adminRepository.save(user);
        return 1;
    }

    @Override
    public User selectByName(String username) {
        return adminRepository.findByUsername(username);
    }

    @Override
    public User selectByEmail(String email) {
        return adminRepository.findByEmail(email);
    }

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        return adminMapper.findByName(s);
    }
}
